import { Component, OnInit, ElementRef, ViewChild, ViewChildren, QueryList } from '@angular/core';
import { BladeContainerBase } from "../../../../shared/blade/blade-container-base";
import { BladeData } from "../../../../shared/blade/blade-data";
import { Blade } from "../../../../shared/blade/blade.model";
import { Command } from "../../../../shared/toolbar.service";
import { DialogResult } from "../../../../shared/dialog.service";
import { Observable } from "rxjs/Observable";
import { Setofkey } from "../../../../entity/setofkey.model";
import { SetofkeyService } from "../../../../service/setofkey.service";
import { ApplicationService } from "../../../../service/application.service";
import { SoundEditComponent } from "../sound-edit/sound-edit.component";
import { AlarmSoundService } from "../../../../service/alarm-sound.service";
import { SoundFile } from "../../../../entity/sound-file.model";
import { FaultLevel } from "../../../../entity/fault-level.model";
import { FaultLevelService } from "../../../../service/fault_level.service";


@Component({
    selector: 'app-sound-list',
    templateUrl: './sound-list.component.html',
    styleUrls: ['./sound-list.component.css']
})
export class SoundListComponent extends BladeContainerBase<SoundFile> {

    // @ViewChild('audio')
    // private audio: ElementRef;
    @ViewChildren('audio')
    audios: QueryList<'audio'>;



    public soundFileData: SoundFile[] = [];
    public original: SoundFile[] = [];
    public currSoundEntity: SoundFile;

    public baseUrl: string;

    private changeSoundId: number;
    private currId: number;
    public styleId: number;
    public isPlay: boolean = true;
    constructor(
        private alarmSoundService: AlarmSoundService,
        private faultLevelService: FaultLevelService,
        private application: ApplicationService

    ) { super(); }

    ngOnInit(): void {
        this.baseUrl = window.location.origin;
        this.baseUrl = this.application.appConfigData.appReport;
        this.baseUrl += '/img/';
        this.commands = [
            new Command("upload", "上传", "fa fa-upload", "setofkey:insert", blade => this.exeAdd(blade), blade => this.canExeAdd(blade)),
            new Command("save", "保存", "fa fa-save", "setofkey:update", (blade) => this.exeSaveChange(blade), (blade) => this.canSaveChange(blade)),
            new Command("delete", "删除", "fa fa-trash-o", "setofkey:delete", blade => this.exeDelete(blade), blade => this.canDelete(blade)),
        ];
        super.ngOnInit();
    }

    initData(): any | Observable<any> | Promise<any> {

        this.alarmSoundService.getAlarmSounds()
            .then(res => {
                if (res) {
                    this.original = [...res];
                }
                this.soundFileData = [...this.original];
                let index = this.soundFileData.findIndex(o => o.soundId === (this.parentEntity as FaultLevel).soundId);
                if (index > -1) {
                    this.currSoundEntity = this.soundFileData[index];
                    this.currId = this.currSoundEntity.soundId;
                    this.styleId = this.currSoundEntity.soundId;
                    this.changeSoundId = this.currSoundEntity.soundId;
                }
            })
            .catch(error => this.bladeData.error = error)
            .then(res => this.bladeData.isLoading = false)

    }

    exeAdd(blend: Blade): void {
        let data: BladeData = new BladeData();
        data.id = "soundCreate";
        data.title = "上传声音文件";
        data.isClosingDisabled = false;
        let createKeyBlade = this.bladeService.createBlade(SoundEditComponent, data, true, null, this.currentEntity);
        this.bladeService.showBlade(createKeyBlade, this.currentBlade);
    }
    canExeAdd(blend: Blade): boolean {
        return true;
    }
    exeDelete(blend: Blade): void {
        let selectedStateGroup = this.getSelected();
        if (selectedStateGroup.length > 0) {
            this.dialogService
                .showConfirmationDialog("确认删除", "是否要删除选中项？")
                .subscribe(dialogResult => {
                    if (dialogResult == DialogResult.Ok) {
                        this.currentBlade.bladeData.isLoading = true;
                        this.alarmSoundService.batchDelete(selectedStateGroup.map(o => o.soundId))
                            .then(res => {
                                if (res) {
                                    this.refresh(undefined);
                                }
                            })
                            .catch(error => this.bladeData.error = error)
                            .then(res => this.bladeData.isLoading = false);
                    }
                })

        }

    }
    canDelete(blend?: Blade): boolean {
        return this.getSelected().length > 0;
    }

    exeSaveChange(blade: any): void {
        this.saveChange();
    }

    canSaveChange(blade: any): boolean {
        return this.changeSoundId !== this.currId;
    }

    onSeletedChange(sound: SoundFile) {
        if (this.currentBlade.childrenCanDeactivate()) {
            this.styleId = sound.soundId;
        }
    }

    onSoundCheack(event: HTMLInputElement, key: SoundFile) {
        this.currSoundEntity = key;
        this.changeSoundId = key.soundId;
    }

    playMusic() {
        this.isPlay = !this.isPlay;
        // if (this.audios..paused) {
        //     this.audio.nativeElement.play();
        // } else {
        //     this.audio.nativeElement.pause();
        // }
    }
    pausedMusic() {
        //this.audio.nativeElement.pause();
    }

    saveChange(): any | Promise<any> | Observable<any> {
        this.parentEntity.soundId = this.changeSoundId;
        if (this.canSaveChange(this.currentBlade)) {
            return this.faultLevelService.update(this.parentEntity as FaultLevel)
                .then(res => {
                    if (res) {
                        (this.parentBlade.bladeContainerInstance).refresh(res);
                        this.bladeService.closeBlade(this.currentBlade);
                        return true;
                    }
                })
                .catch(error => this.bladeData.error = error)
                .then(res => this.bladeData.isLoading = false);
        }
    }

	/**
     * 单选
     *
     * @param {any} event
     * @param {any} key
     *
     * @memberof MatrixStateGroupListComponent
     */
    onItemCheack(event: HTMLInputElement, key: SoundFile) {
        key.isChecked = event.checked;
    }

	/**
     * 全选/全不选
     *
     * @param {HTMLInputElement} event
     *
     * @memberof MatrixStateGroupListComponent
     */
    onAllCheack(event: HTMLInputElement) {
        if (this.soundFileData.length > 0) {
            for (let i = 0; i < this.soundFileData.length; i++) {
                this.soundFileData[i].isChecked = event.checked;
            }
        }
    }
    /**
    * 获得选中项
    *
    * @returns {Setofkey[]}
    *
    * @memberof MatrixStateGroupListComponent
    */
    getSelected(): SoundFile[] {
        if (this.soundFileData.length > 0) {
            let filter = this.soundFileData.filter(ref => ref.isChecked);
            return filter == null ? [] : filter;
        }
        return [];
    }

}



// WEBPACK FOOTER //
// ./src/app/module/basic/sound/sound-list/sound-list.component.ts
